let express=require("express");
const app=express();
const cors=require("cors")
app.use(cors())
const server=require("http").createServer(app);
const io=require("socket.io")(server,{cors:true})
//这里暂时存储十条数据
const msgArr=[];
/**
 * 用户初始化消息列表
 */
app.get('/msgList',(req,res)=>{
    res.send(JSON.stringify({data:msgArr,code:200}));
})
io.on("connection",socket=>{
    socket.broadcast.emit("totalRefresh",io.engine.clientsCount);
    socket.emit("totalRefresh",io.engine.clientsCount);
    socket.on("sendMsg",o=>{
        // 数据大于10条直接删除第一条
        if(msgArr.length>10){
            msgArr.splice(0,1);
        }
        msgArr.push(o);
        socket.broadcast.emit("serverToClient",o)
    })
    socket.on("disconnect",()=>{
        socket.broadcast.emit("totalRefresh",io.engine.clientsCount);
    })
})
server.listen(8888,()=>{
    console.log('Server Running at localhost:8888');
})